package ru.csat.jmsmonitor;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.PropertyConfigurator;

import javax.naming.Context;
import java.io.FileInputStream;
import java.util.Hashtable;
import java.util.Properties;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * User: A.Senatorov
 * Date: 19.11.12
 * Time: 10:32
 * To change this template use File | Settings | File Templates.
 */
public class Service {
    private static Properties properties;
    private static Log log = LogFactory.getLog(Main.class);
    private static Hashtable<String, String> env = new Hashtable<>();
    private ScheduledExecutorService jmsService;
    private static volatile Service instance;

    static {
        properties = new Properties();
        System.out.println(System.getProperty("user.dir"));
        String bridgePropFileName = System.getProperty("user.dir") + System.getProperty("file.separator") + "app.properties";
        String log4jropFileName = System.getProperty("user.dir") + System.getProperty("file.separator") + "log4j.properties";

        try {
            PropertyConfigurator.configure(new FileInputStream(log4jropFileName));
            properties.load(new FileInputStream(bridgePropFileName));

            env.put(Context.PROVIDER_URL, properties.getProperty("jnp"));
            env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
            env.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");

            log.info("prop loaded");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    public static Service getInstance() {
        Service localInstance = instance;
        if (localInstance == null) {
            synchronized (Service.class) {
                localInstance = instance;
                if (localInstance == null) {
                    instance = localInstance = new Service();
                }
            }
        }
        return localInstance;
    }

    private Service() {
        try {
            jmsService = Executors.newSingleThreadScheduledExecutor();
            jmsService.scheduleAtFixedRate(new Task(), 1000, Long.valueOf(properties.getProperty("ping_period_ms")), TimeUnit.MILLISECONDS);
            log.info("jms scheduler started");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    public static Properties getProperties() {
        return properties;
    }

    public static Hashtable<String, String> getEnv() {
        return env;
    }
}
